from Tkinter import *
import numpy as np
import os, time,socket,sys,json

payloads=["km","menge","preis"]

def set_date():
	datafields["date"].delete(0,END)
	datafields["date"].insert(0,str(round(1000*time.time())))

def send_data():
	json_out={"device":socket.gethostname(),"payload":{}}
	for x in payloads:
		json_out["payload"][x]={"time":0,"sensor":"rechnung","value":0,"i2c":0}
	local_time=round(1000*time.time())
	try:
		local_time=int(datafields["date"].get())
	except:
		local_time=round(1000*time.time())
	local_kfz="berlingo"
	try:
		local_kfz=datafields["kfz"].get()
	except:
		local_kfz="berlingo"
	for x in payloads:
		try:
			json_out["payload"][x]["value"]=int(datafields[x].get())
		except:
			del(json_out["payload"][x])
			print("kein ",x)
		else:
			json_out["payload"][x]["time"]=local_time
			json_out["payload"][x]["sensor"]=local_kfz
	if len(json_out["payload"])>0:
		try:
			s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		except:
			print("{}: could not connect to database".format(time.time()))
		else:
			try:
				s.connect(("banana", 24048))
			except:
				print("{}: could not connect to database".format(time.time()))
			else:
				s.sendall(json.dumps(json_out))
				s.close()
	print(json_out)

json_out={"device":socket.gethostname(),"payload":{}}
for x in payloads:
	json_out["payload"][x]={"time":0,"sensor":"rechnung","value":0,"i2c":0}

groot=Tk()
groot.wm_title("KFZ aufnehmen")
groot.config(background="#FFFFFF")
gframe=Frame(groot,width=400,height=300)
gframe.grid(row=0,column=0,padx=10,pady=3)

button_date=Button(gframe,text="Epoch",bg="#FF0000",width=15,command=set_date)
button_date.grid(row=0,column=0,padx=10,pady=3)
label_kfz=Label(gframe,text="KFZ")
label_kfz.grid(row=1,column=0,padx=10,pady=3)
label_km=Label(gframe,text="km")
label_km.grid(row=2,column=0,padx=10,pady=3)
label_menge=Label(gframe,text="Volumen")
label_menge.grid(row=3,column=0,padx=10,pady=3)
label_preis=Label(gframe,text="Preis")
label_preis.grid(row=4,column=0,padx=10,pady=3)

datafields={}
felder=["date","kfz","km","menge","preis"]
for x in range(len(felder)):
	datafields[felder[x]]=Entry(gframe,width=18)
	datafields[felder[x]].grid(row=x,column=1,padx=10,pady=3)

button_send=Button(gframe,text="Absenden",bg="#00FF00",width=15,command=send_data)
button_send.grid(row=5,column=1,padx=10,pady=3)

datafields["date"].insert(0,str(round(1000*time.time())))
datafields["kfz"].insert(0,"berlingo")

groot.mainloop()
